<template>
  <div class="live-start-page">
    <div class="page-header">
      <div class="header-left">
        <el-page-header @back="goBack">
          <template #content>开始直播</template>
        </el-page-header>
      </div>
    </div>

    <div class="page-content">
      <el-row :gutter="20">
        <!-- 左侧预览区域 -->
        <el-col :span="16">
          <el-card class="preview-card">
            <template #header>
              <div class="card-header">
                <span>直播控制</span>
                <div class="header-actions">
                  <el-button
                    v-if="!isLiving"
                    type="primary"
                    :loading="startLoading"
                    @click="handleStartLive"
                  >
                    <el-icon><VideoPlay /></el-icon>
                    开始直播
                  </el-button>
                  <el-button
                    v-else
                    type="danger"
                    :loading="stopLoading"
                    @click="handleStopLive"
                  >
                    <el-icon><VideoPause /></el-icon>
                    结束直播
                  </el-button>
                </div>
              </div>
            </template>

            <div class="preview-container">
              <!-- 视频预览区域 -->
              <div class="video-container" id="video-container">
                <!-- <video  class="preview-video" id="preview-Screen"></video> -->
                <video
                  id="preview-video"
                  class="preview-video"
                  controls
                ></video>
              </div>

              <!-- 状态信息 -->
              <div class="status-container">
                <div class="status-info">
                  <div class="status-item">
                    <label>直播状态：</label>
                    <el-tag :type="isLiving ? 'success' : 'info'">
                      {{ isLiving ? "直播中" : "未开播" }}
                    </el-tag>
                  </div>
                  <div class="status-item">
                    <label>在线人数：</label>
                    <span>{{ onlineCount }}</span>
                  </div>
                  <div class="status-item">
                    <label>直播时长：</label>
                    <span>{{ liveTime }}</span>
                  </div>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 右侧设置区域 -->
        <el-col :span="8">
          <el-card class="setting-card">
            <template #header>
              <div class="card-header">
                <span>直播设置</span>
              </div>
            </template>

            <live-setting ref="settingRef" @update="handleSettingUpdate" />
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onBeforeMount, onMounted, onUnmounted, ref } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { VideoPlay, VideoPause, VideoCamera } from "@element-plus/icons-vue";
import LiveSetting from "../components/LiveSetting.vue";
import type { LiveSetting as LiveSettingType } from "@/apis/live";
import LiveStream from "@/utils/live/live";
import { nextTick } from "process";
import {
  CameraFace,
  screenFace,
  configType,
  configTypes,
} from "@/tyeps/OvenLiveKit";
const router = useRouter();
const settingRef = ref();
const videoRef = ref<HTMLVideoElement>();
const startLoading = ref(false);
const stopLoading = ref(false);
const isLiving = ref(false);
const onlineCount = ref(0);
const liveTime = ref("00:00:00");
const LiveClient = ref<LiveStream>();
const configTypeIndex = ref<number>(0);
const datas = ref<configTypes>([
  {
    video: true,
    audio: false,
    isVideo: false,
    isAudio: false,
    type: "Camera",
    stream: null,
    id: "",
    isStop: false,
    x: 500,
    y: 0,
    scale: 0.5,
    videoTexture: null,
  },
  {
    video: true,
    audio: false,
    isVideo: false,
    isAudio: false,
    type: "Screen",
    stream: null,
    id: "",
    isStop: false,
    x: 0,
    y: 0,
    scale: 1,
    videoTexture: null,
  },
]);
let timer: ReturnType<typeof setInterval> | null = null;

// 返回上一页
const goBack = () => {
  if (isLiving.value) {
    ElMessage.warning("请先结束直播");
    return;
  }
  router.back();
};

// 开始直播
const handleStartLive = async () => {
  if (!settingRef.value) return;

  startLoading.value = true;
  try {
    const valid = await settingRef.value.handleSubmit();
    if (!valid) {
      ElMessage.warning("请完善直播设置");
      return;
    }
    console.log(window);
    // TODO: 调用开播API
    await new Promise((resolve) => setTimeout(resolve, 1000));

    isLiving.value = true;
    ElMessage.success("开播成功");

    // 开始计时
    let seconds = 0;
    timer = setInterval(() => {
      seconds++;
      const hours = Math.floor(seconds / 3600);
      const minutes = Math.floor((seconds % 3600) / 60);
      const secs = seconds % 60;
      const hoursStr = hours.toString().padStart(2, "0");
      const minutesStr = minutes.toString().padStart(2, "0");
      const secsStr = secs.toString().padStart(2, "0");
      liveTime.value = hoursStr + ":" + minutesStr + ":" + secsStr;
    }, 1000);

    // 设置视频源
    if (videoRef.value && settingRef.value?.settingForm?.value?.RoomAddress) {
      videoRef.value.src = settingRef.value.settingForm.value.RoomAddress;
    }
  } catch (error) {
    console.error("开播失败:", error);
  } finally {
    startLoading.value = false;
  }
};

// 结束直播
const handleStopLive = async () => {
  stopLoading.value = true;
  try {
    // TODO: 调用关播API
    await new Promise((resolve) => setTimeout(resolve, 1000));

    isLiving.value = false;
    ElMessage.success("已结束直播");

    // 停止计时
    if (timer) {
      clearInterval(timer);
      timer = null;
    }
    liveTime.value = "00:00:00";
    onlineCount.value = 0;

    // 清除视频源
    if (videoRef.value) {
      videoRef.value.src = "";
    }
  } catch (error) {
    console.error("关播失败:", error);
    ElMessage.error("关播失败");
  } finally {
    stopLoading.value = false;
  }
};

// 设置更新回调
const handleSettingUpdate = (setting: LiveSettingType) => {
  console.log("设置已更新:", setting);
};
// const resizeObserver = new ResizeObserver((entries) => {
//   entries.forEach(entry => {
//     // 获取元素的宽度和高度
//     // const width = entry.contentRect.width;
//     // const height = entry.contentRect.height;
//     // console.log(`元素宽度: ${width}px, 高度: ${height}px`);
//     LiveClient.value?.change()
//   });
// });
const show = async () => {
  const d = datas.value[configTypeIndex.value];
  if (d.type === "Camera") {
    await LiveStream.getUserMedia(d);
  } else {
    await LiveStream.getDisplayMedia(d);
  }
  const ws =
    "ws://192.168.86.18:3333/app/f1077452-6476-47be-aca2-f70005744467?direction=send";
  LiveClient.value = new LiveStream("preview-video", ws);
  if (d.stream) await LiveClient.value?.setMediaStream(d.stream);
};
onMounted(() => {
  nextTick(() => {
    show();
  });
});
onUnmounted(() => {
  LiveClient.value?.remove();
  const d = datas.value[configTypeIndex.value];
  if (d.stream) LiveStream.StreamStop(d.stream)
});
</script>

<style scoped lang="scss">
.live-start-page {
  padding: 16px;
  height: 100%;
  display: flex;
  flex-direction: column;

  .page-header {
    margin-bottom: 16px;
  }

  .page-content {
    flex: 1;
    min-height: 0;

    .preview-card,
    .setting-card {
      height: 100%;

      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .header-actions {
          .el-button {
            .el-icon {
              margin-right: 4px;
            }
          }
        }
      }
    }

    .preview-container {
      height: calc(100% - 60px);
      display: flex;
      flex-direction: column;
      gap: 16px;

      .video-container {
        flex: 1;
        min-height: 0;
        background-color: #000;
        position: relative;
        border-radius: 4px;
        // overflow: hidden;

        .preview-video {
          height: 100%;
          object-fit: contain;
          width: 100%; /* 宽度为100% */
          aspect-ratio: 16 / 9; /* 设置宽高比为 16:9 */
          // background-color: lightblue; /* 给元素添加背景颜色 */
        }
        .preview-canvas {
          width: 100%;
          height: 396.73px;
          object-fit: contain;
        }

        .video-placeholder {
          position: absolute;
          left: 0;
          top: 0;
          width: 100%;
          height: 100%;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          color: #fff;
          background-color: rgba(0, 0, 0, 0.5);

          .el-icon {
            font-size: 48px;
            margin-bottom: 16px;
          }

          p {
            margin: 0;
            font-size: 16px;
          }
        }
      }

      .status-container {
        display: flex;
        align-items: center;
        justify-content: center;

        .status-info {
          display: flex;
          gap: 24px;

          .status-item {
            display: flex;
            align-items: center;
            gap: 8px;

            label {
              color: var(--el-text-color-secondary);
              width: 80px;
              text-align: right;
            }

            span {
              color: var(--el-text-color-primary);
              font-family: monospace;
              font-size: 16px;
            }
          }
        }
      }
    }

    .setting-card {
      :deep(.el-card__body) {
        height: calc(100% - 60px);
        overflow-y: auto;
      }
    }
  }
}
</style>
